package com.partner.match.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.partner.match.common.ErrorCode;
import com.partner.match.constant.UserConstant;
import com.partner.match.exception.BusinessException;
import com.partner.match.mapper.TeamMapper;
import com.partner.match.mapper.UserTeamMapper;
import com.partner.match.model.entity.Team;
import com.partner.match.model.entity.User;
import com.partner.match.model.entity.UserTeam;
import com.partner.match.model.enums.UserRoleEnum;
import com.partner.match.model.vo.LoginUserVO;
import com.partner.match.service.UserTeamService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @author jzz
 * @description 针对表【user_team(用户队伍关系表)】的数据库操作Service实现
 * @createDate 2025-01-25 10:32:01
 */
@Service
public class UserTeamServiceImpl extends ServiceImpl<UserTeamMapper, UserTeam>
        implements UserTeamService {
    @Resource
    private TeamMapper teamMapper;
    @Resource
    private UserTeamMapper userTeamMapper;

    @Override
    public Long createRelation(Long teamId, Long userId) {
        if(teamId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 队伍是否存在
        Team team = teamMapper.selectById(teamId);
        if(ObjectUtil.isNull(team)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"队伍不存在");
        }

        UserTeam userTeam = new UserTeam();
        userTeam.setTeamId(teamId);
        userTeam.setUserId(userId);
        boolean saved = this.save(userTeam);
        if (!saved) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"创建用户-队伍关系失败");
        }
        return userTeam.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exitTeam(Long teamId) {
        Team team = teamMapper.selectById(teamId);
        if(ObjectUtil.isNull(team)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"队伍不存在");
        }
        // 当前登录用户
        User user = (User) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);

        QueryWrapper<UserTeam> userTeamQW = null;
        // 是否已经退出队伍
        userTeamQW = new QueryWrapper<>();
        userTeamQW.eq(UserTeam.TEAM_ID, teamId);
        userTeamQW.eq(UserTeam.USER_ID,user.getUserId());
        UserTeam selectOne = userTeamMapper.selectOne(userTeamQW);
        if(ObjectUtil.isNull(selectOne)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"已经退出该队伍");
        }

        // 队伍如果只剩一人，直接解散
        userTeamQW = new QueryWrapper<>();
        userTeamQW.eq(UserTeam.TEAM_ID, teamId);
        Long count = userTeamMapper.selectCount(userTeamQW);
        if(count == 1){
            userTeamMapper.delete(userTeamQW);
            teamMapper.deleteById(teamId);
        }

        // 队伍还有其他人
        // 如果是普通用户，直接退出
        if(!Objects.equals(team.getUserId(),user.getUserId())){
            userTeamQW = new QueryWrapper<>();
            userTeamQW.eq(UserTeam.TEAM_ID, teamId);
            userTeamQW.eq(UserTeam.USER_ID,user.getUserId());
            int deleted = userTeamMapper.delete(userTeamQW);
            if(deleted != 1){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"退出失败");
            }
        }

        // 如果是队长，将队长身份转移给第二早进队的人
        if(Objects.equals(team.getUserId(), user.getUserId())){
            Long leaderId = userTeamMapper.queryLeader(teamId,user.getUserId());
            team.setUserId(leaderId);
            int updated = teamMapper.updateById(team);
            if(updated != 1){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"转移队长失败");
            }
            userTeamQW = new QueryWrapper<>();
            userTeamQW.eq(UserTeam.TEAM_ID, teamId);
            userTeamQW.eq(UserTeam.USER_ID,user.getUserId());
            int deleted = userTeamMapper.delete(userTeamQW);
            if(deleted != 1){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"退出失败");
            }
        }

    }
}




